<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-23
 * Time: 19:15
 */

namespace app\api\service\store;


use app\api\model\StoreOrder;
use app\api\model\StoreOrderClean;
use app\api\model\User;
use app\api\service\Token;
use app\api\validate\order\CheckStaffOrder;
use app\lib\exception\ParameterException;
use think\Db;
use think\Exception;

class StaffClearOrderSer extends Token
{
    /**
     *  1.传入的判断数据
     *  1.判断是否是取送员
     *  2.判断订单信息以及 取送员是否一致
     *  3.修改订单状态 - 添加取衣清单
     */

    // 订单信息
    private $order;

    // 订单价格
    private $price;

    // 取送员信息
    private $staff;

    // 取衣清单
    private $cleanArr;

    // 构造方法
    function __construct($orderId,$price,$clean)
    {
        $this->order = StoreOrder::get($orderId);
        $this->price = $price;
        $this->cleanArr = $clean;
    }

    // 入口文件
    public function entrance()
    {
        (new CheckStaffOrder())->goCheck();
        $user = User::get(self::getCurrentUid());
        $this->staff = self::judgeStaff($user);
        return $this->judgeOrder();
    }

    // 判断订单
    public function judgeOrder()
    {
        if(!$this->order) {
            throw new ParameterException([
                'msg' => [
                    'store_order' => '请重新选择订单'
                ]
            ]);
        }
        if($this->order['status'] != 2) {
            throw new ParameterException([
                'msg' => [
                    'store_order' => '订单状态错误'
                ]
            ]);
        }
        if($this->order['pick_deliver_staff_id'] != $this->staff['id']) {
            throw new ParameterException([
                'msg' => [
                    'store_order' => '该订单不是您的'
                ]
            ]);
        }
        return $this->updateOrder();
    }

    // 修改订单 并添加取衣清单
    private function updateOrder()
    {
        Db::startTrans();
        try{
            $storeOrder = new StoreOrder();
            $storeOrder->save([ 'price'=> $this->price, 'status'=>3, 'clear_time'=> time() ],[ 'id' => $this->order['id'] ]);
            foreach ($this->cleanArr as $k=>$v) {
                $this->cleanArr[$k]['store_order_id'] = $this->order['id'];
            }
            $storeOrderClean = new StoreOrderClean();
            $storeOrderClean->allowField(true)->saveAll( $this->cleanArr);
            Db::commit();
            return writeJson(202, [], '提交成功！');
        }
        catch (Exception $ex) {
            Db::rollback();
            throw $ex;
        }
    }
}